package com.lcc.bank.tools.util.config;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.configuration.AbstractConfiguration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;

/**
 * @author lcc
 * @date 2017年6月12日
 * 属性文件加载工具类，属性文件更改时，会自动重新加载
 */
public class PropertiesLoader {
	private static Map<String, PropertiesConfiguration> propertiesConfigurationCache = new ConcurrentHashMap<String, PropertiesConfiguration>();
	private static Map<String, XMLConfiguration> XmlConfigurationCache = new ConcurrentHashMap<String, XMLConfiguration>();

	static {
		AbstractConfiguration.setDefaultListDelimiter('|');
	}

	/**
	 * 读取指定的属性文件
	 *
	 * @param configFileName
	 *            属性文件名称，无“.properties”后缀
	 * @return 属性配置对象
	 */
	public synchronized static PropertiesConfiguration getConfiguration(
			String configFileName) {
		if (propertiesConfigurationCache.containsKey(configFileName)) {
			return propertiesConfigurationCache.get(configFileName);
		} else {
			try {
				PropertiesConfiguration config = new PropertiesConfiguration(
						configFileName + ".properties");
				// 设置属性文件更改时，自动更新
				config.setReloadingStrategy(new FileChangedReloadingStrategy());
				propertiesConfigurationCache.put(configFileName, config);
				return config;
			} catch (ConfigurationException e) {

			}
			return null;
		}
	}

	public synchronized static XMLConfiguration getXmlConfiguration(
			String configFileName) {
		if (XmlConfigurationCache.containsKey(configFileName)) {
			return XmlConfigurationCache.get(configFileName);
		} else {
			try {
				XMLConfiguration config = new XMLConfiguration(configFileName
						+ ".xml");
				// 设置属性文件更改时，自动更新
				config.setReloadingStrategy(new FileChangedReloadingStrategy());
				XmlConfigurationCache.put(configFileName, config);
				return config;
			} catch (ConfigurationException e) {
				System.out.println(e.getMessage());
			}
			return null;
		}
	}

}
